<?php
/*
 * 模版编译加载类
 * @package    system
 * @author     Mark
 * @copyright  Copyright (c) 2013 ixdcw team
 * @version    $Id: 73b2842988fe3d5649e2c9efcb4964fc96f10435 $
 */
class Template {

	/**
	 *
	 * @param $content
	 */
	public static function preview($content) {
		$tpl_content = stripslashes($content);
		$tpl_content = template_parse($tpl_content);
		PCache::write('_preview.tpl.php', $tpl_content, 'tpl');
		include DT_CACHE . '/tpl/_preview.tpl.php';
		exit();
	}

	/**
	 * 获取处理过的地址
	 * @param        $template
	 * @param string $dir
	 * @return string
	 */
	public static function ob($template, $dir = '') {
		ob_start();
		include template($template, $dir);
		$contents = ob_get_contents();
		ob_clean();
		return $contents;
	}

	/**
	 * tag标签函数
	 * @param     $parameter
	 * @param int $expires
	 * @return array|string
	 */
	public static function tag($parameter, $expires = 0) {
		global $DT, $CFG, $MODULE, $DT_TIME, $db;
		if($expires > 0) {
			$tag_expires = $expires;
		} else if($expires == -2) {
			$tag_expires = $CFG['db_expires'];
		} else if($expires == -1) {
			$tag_expires = 0;
		} else {
			$tag_expires = $CFG['tag_expires'];
		}

		$tag_cache = false;
		$db_cache = ($expires == -2 || defined('TOHTML')) ? 'CACHE' : '';

		if($tag_expires && $db_cache != 'CACHE' && strpos($parameter, '&page=') === false) {
			$tag_cache = true;
			$TCF = DT_CACHE.'/tag/'.md5($parameter).'.htm';
			if(is_file($TCF) && ($DT_TIME - filemtime($TCF) < $tag_expires)) {
				echo substr(File::get($TCF), 17);
				return;
			}
		}
		$parameter = str_replace(array('&amp;'), array(''), $parameter);
		parse_str($parameter, $par);
		if(!is_array($par)) return '';
		$par = Str::stripSlashes($par);
		extract($par);
		/** @var 数据库表前缀  */
		isset($prefix) or $prefix = $db->getPre();
		/** @var 模版id  */
		isset($moduleid) or $moduleid = 1;
		if(!isset($MODULE[$moduleid])) return '';
		/** @var 查询的字段  */
		isset($fields) or $fields = '*';
		/** @var 分类id  */
		isset($catid) or $catid = 0;
		/** @var 是否包含子分类  */
		isset($child) or $child = 1;
		/** @var 地区id  */
		isset($areaid) or $areaid = 0;
		/** @var 是否包含下属地区  */
		isset($areachild) or $areachild = 1;
		/** @var 文件存放目录  */
		isset($dir) or $dir = 'tag';
		/** @var 模版名称  */
		isset($template) or $template = 'list';
		/** @var 查询限制条件  */
		isset($condition) or $condition = '1';
		/** @var 会员组类别  */
		isset($group) or $group = '';
		/** @var 页数  */
		isset($page) or $page = 1;
		/** @var 起始数据条数  */
		isset($offset) or $offset = 0;
		/** @var 每页条数  */
		isset($pagesize) or $pagesize = 10;
		/** @var 排序  */
		isset($order) or $order = '';
		/** @var 显示页数  */
		isset($showpage) or $showpage = 0;
		/** @var 是否统计数据的分类名称和连接地址  */
		isset($showcat) or $showcat = 0;
		/** @var 日期显示格式  */
		isset($datetype) or $datetype = 0;
		/** @var html标签  */
		isset($target) or $target = '';
		/*  */
		isset($class) or $class = '';
		/** @var 返回如果读取的数据有title 及 company项，那么其读取的长度  */
		isset($length) or $length = 0;
		/** @var 如果读取的数据有introduce项，那么其长度  */
		isset($introduce) or $introduce = 0;
		/** @var 输出sql语句测试  */
		isset($debug) or $debug = 0;
		isset($linkShowChilds) or $linkShowChilds = 0;
		(isset($cols) && $cols) or $cols = 1;
		if($catid && $moduleid > 4) {
			if(is_numeric($catid)) {
				$CAT = $db->getOne("SELECT child,arrchildid,moduleid FROM {$db->getPre()}category WHERE catid=$catid");
				$condition .= ($child && $CAT['child'] && $CAT['moduleid'] == $moduleid) ? " AND catid IN (".$CAT['arrchildid'].")" : " AND catid=$catid";
			} else {
				if($child) {
					$catids = '';
					$sql = "SELECT arrchildid FROM {$db->getPre()}category WHERE catid IN ($catid)";
					//echo $sql;
					$result = $db->query($sql);
					while($r = $db->fetchArray($result)) {
						$catids .= ','.$r['arrchildid'];
					}
					if($catids) $catid = substr($catids, 1);
				}
				$condition .= " AND catid IN ($catid)";
			}
		}
		if($areaid) {
			if(is_numeric($areaid)) {
				$ARE = $db->getOne("SELECT child,arrchildid FROM {$db->getPre()}area WHERE areaid=$areaid", 'CACHE');
				$condition .= ($areachild && $ARE['child']) ? " AND areaid IN (".$ARE['arrchildid'].")" : " AND areaid=$areaid";
			} else {
				if($areachild) {
					$areaids = '';
					$result = $db->query("SELECT arrchildid FROM {$db->getPre()}area WHERE areaid IN ($areaid)");
					while($r = $db->fetchArray($result)) {
						$areaids .= ','.$r['arrchildid'];
					}
					if($areaids) $areaid = substr($areaids, 1);
				}
				$condition .= " AND areaid IN ($areaid)";
			}
		}

		//获得数据所在目标 表文件
		$table = isset($table) ? $prefix.$table : get_table($moduleid);
		//获得数据条数
		$offset or $offset = ($page-1)*$pagesize;
		//echo $offset;
		//$percent = dround(100/$cols).'%';
		$num = 0;
		$order = $order ? ' ORDER BY '.$order : '';
		$condition = stripslashes($condition);
		$condition = str_replace('##', '%', $condition);
		if($showpage) {
			$num = $db->count($table, $condition, $tag_expires ? $tag_expires : $CFG['db_expires']);
			$pages = pages($num, $page, $pagesize);
		} else {
			if($group) $condition .= ' GROUP BY '.$group;
		}
		if($page < 2 && strpos($parameter, '&page=') !== false) {
			$db_cache = 'CACHE';
			$tag_expires = $CFG['tag_expires'];
		}
		if($template == 'null') $db_cache = 'CACHE';
		$query = "SELECT ".$fields." FROM ".$table." WHERE ".$condition.$order." LIMIT ".$offset.",".$pagesize;
		if($debug) echo $parameter.'<br/>'.$query.'<br/>';
		$tags = $catids = $CATS = array();
		$result = $db->query($query, $db_cache, $tag_expires);
		while($r = $db->fetchArray($result)) {
			if($moduleid == 4 && isset($r['company'])) {
				$r['alt'] = $r['companyname'] = $r['company'];
				if($length) $r['company'] = Str::cut($r['company'], $length);
			}
			if(isset($r['title'])) {
				$r['title'] = str_replace('"', '&quot;', trim($r['title']));
				$r['alt'] = $r['title'];
				if($length) $r['title'] = Str::cut($r['title'], $length);
				if(isset($r['style']) && $r['style']) $r['title'] = set_style($r['title'], $r['style']);
			}
			if(isset($r['introduce']) && $introduce) $r['introduce'] = Str::cut($r['introduce'], $introduce);
			if(isset($r['linkurl']) && $r['linkurl'] && $moduleid > 4 && strpos($r['linkurl'], '://') === false) $r['linkurl'] = $MODULE[$moduleid]['linkurl'].$r['linkurl'];
			if($showcat && $moduleid > 4 && isset($r['catid'])) $catids[$r['catid']] = $r['catid'];
			$tags[] = $r;
		}
		$db->freeResult($result);
		if($showcat && $moduleid > 4 && $catids) {
			$result = $db->query("SELECT catid,catname,linkurl FROM {$db->getPre()}category WHERE catid IN (".implode(',', $catids).")");
			while($r = $db->fetchArray($result)) {
				$CATS[$r['catid']] = $r;
			}
			if($CATS) {
				foreach($tags as $k=>$v) {
					$tags[$k]['catname'] = $v['catid'] ? $CATS[$v['catid']]['catname'] : '';
					$tags[$k]['caturl'] = $v['catid'] ? $MODULE[$moduleid]['linkurl'].$CATS[$v['catid']]['linkurl'] : '';
				}
			}
		}

		if($template == 'null') return $tags;
		if($tag_cache) {
			ob_start();
			include template($template, $dir);
			$contents = ob_get_contents();
			ob_clean();
			File::put($TCF, '<!--'.($DT_TIME + $tag_expires).'-->'.$contents);
			echo $contents;
		} else {
			include template($template, $dir);
		}
	}
}